package servlet;

import service.UserService;
import model.User;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/profile/password")
public class PasswordServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 添加字符编码设置
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 检查用户登录状态
        User currentUser = SessionUtils.getCurrentUser(request);
        if (currentUser == null) {
            response.sendRedirect("/login.html");
            return;
        }

        // 获取表单数据
        String oldPassword = request.getParameter("oldPassword");
        String newPassword = request.getParameter("newPassword");

        // 验证输入
        if (oldPassword == null || oldPassword.isEmpty() || newPassword == null || newPassword.isEmpty()) {
            User user = userService.findById(currentUser.getId());
            request.setAttribute("user", user);
            request.setAttribute("error", "密码不能为空");
            // 修改为正确的JSP路径
            request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
            return;
        }

        // 验证新密码长度
        if (newPassword.length() < 6) {
            User user = userService.findById(currentUser.getId());
            request.setAttribute("user", user);
            request.setAttribute("error", "新密码长度不能少于6位");
            // 修改为正确的JSP路径
            request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
            return;
        }

        // 更新密码
        boolean success = userService.updatePassword(currentUser.getId(), oldPassword, newPassword);
        
        // 重新获取用户信息
        User user = userService.findById(currentUser.getId());
        
        if (success) {
            request.setAttribute("user", user);
            request.setAttribute("success", "密码更新成功");
        } else {
            request.setAttribute("user", user);
            request.setAttribute("error", "当前密码错误，密码更新失败");
        }
        
        // 修改为正确的JSP路径
        request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response);
    }
}